<template>
  <div class="app-container">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>Dify应用配置管理</span>
          <el-button type="primary" icon="el-icon-plus" @click="handleAdd" size="small">
            新增配置
          </el-button>
        </div>
      </template>

      <!-- 表格数据 -->
      <el-table :data="configList" border stripe :header-cell-style="{ backgroundColor: '#409EFF', color: '#fff', fontWeight: 'bold' }" style="width: 100%">
        <el-table-column type="index" label="序号" width="80" />
        <el-table-column prop="appName" label="应用名称" width="180" />
        <el-table-column prop="apiUrl" label="API地址" />
        <el-table-column prop="description" label="描述" />
        <el-table-column prop="displayOrder" label="显示顺序" width="150" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.displayOrder" :min="0" size="small" @change="handleUpdateOrder(scope.row)" />
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(scope.row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="200">
          <template slot-scope="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="修改时间" width="200">
          <template slot-scope="scope">
            {{ formatDate(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template slot-scope="scope">
            <el-button type="primary" size="small" @click="handleEdit(scope.row)" icon="el-icon-edit">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(scope.row.id)" icon="el-icon-delete">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="600px">
      <el-form :model="form" :rules="rules" ref="formRef" label-width="120px">
        <el-form-item label="应用名称" prop="appName">
          <el-input v-model="form.appName" placeholder="请输入应用名称" />
        </el-form-item>
        <!-- 隐藏应用ID和API密钥字段，通过API地址直接调用 -->
        <!-- API地址字段已移到前面 -->
        <el-form-item label="API地址" prop="apiUrl">
          <el-input v-model="form.apiUrl" placeholder="请输入Dify API地址" />
        </el-form-item>
        <el-form-item label="应用描述" prop="description">
          <el-input v-model="form.description" placeholder="请输入应用描述" type="textarea" :rows="3" />
        </el-form-item>
        <el-form-item label="显示顺序" prop="displayOrder">
          <el-input-number v-model="form.displayOrder" :min="0" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-text="启用"
            inactive-text="禁用"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getDifyConfigList, saveDifyConfig, updateDifyConfig, deleteDifyConfig, updateDifyConfigStatus } from '@/api/dify/manage'

export default {
  name: 'DifyConfigManage',
  data() {
    return {
      configList: [],
      dialogVisible: false,
      dialogTitle: '新增配置',
      form: {
        id: '',
        appName: '',
        appId: '', // 保留但不显示，用于后端兼容
        apiKey: '', // 保留但不显示，用于后端兼容
        apiUrl: '',
        description: '',
        displayOrder: 0,
        status: 1
      },
      rules: {
        appName: [
          { required: true, message: '请输入应用名称', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字符', trigger: 'blur' }
        ],
        apiUrl: [
          { required: true, message: '请输入API地址', trigger: 'blur' },
          { type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.loadData()
  },
  methods: {
    // 加载数据
    loadData() {
      // 使用正确导入的API方法
      getDifyConfigList().then(response => {
        // 确保传递给表格的数据是数组类型
        this.configList = Array.isArray(response.data.data) ? response.data.data : (Array.isArray(response.data) ? response.data : [])
      })
    },
    // 新增配置
    handleAdd() {
      this.dialogTitle = '新增配置'
      this.form = {
        id: '',
        appName: '',
        appId: 'hidden', // 固定值，用于后端兼容
        apiKey: 'hidden', // 固定值，用于后端兼容
        apiUrl: '',
        description: '',
        displayOrder: 0,
        status: 1
      }
      this.dialogVisible = true
    },
    // 编辑配置
    handleEdit(row) {
      this.dialogTitle = '编辑配置'
      // 确保appId不为空且唯一
      if (!row.appId || row.appId === 'hidden') {
        row.appId = 'hidden_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
        row.apiKey = row.appId
      }
      this.form = { ...row }
      this.dialogVisible = true
    },
    // 提交表单
    handleSubmit() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const submitData = { ...this.form }
          // 确保appId不为空且唯一
          if (!submitData.appId || submitData.appId === 'hidden') {
            submitData.appId = 'hidden_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)
            submitData.apiKey = submitData.appId
          }
          
          if (submitData.id) {
            updateDifyConfig(submitData).then(() => {
              this.$message.success('更新成功')
              this.dialogVisible = false
              this.loadData()
            })
          } else {
            saveDifyConfig(submitData).then(() => {
              this.$message.success('保存成功')
              this.dialogVisible = false
              this.loadData()
            })
          }
        }
      })
    },
    // 删除配置
    handleDelete(id) {
      this.$confirm('确定要删除该配置吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteDifyConfig(id).then(() => {
          this.$message.success('删除成功')
          this.loadData()
        })
      })
    },
    // 状态切换
    handleStatusChange(row) {
      updateDifyConfigStatus(row.id, row.status).then(() => {
        this.$message.success('状态更新成功')
      }).catch(() => {
        this.loadData() // 失败时刷新数据
      })
    },
    // 更新显示顺序
    handleUpdateOrder(row) {
      updateDifyConfig(row).then(() => {
        this.$message.success('顺序更新成功')
      })
    },
    // 格式化日期时间
    formatDate(date) {
      if (!date) return ''
      const d = new Date(date)
      const year = d.getFullYear()
      const month = String(d.getMonth() + 1).padStart(2, '0')
      const day = String(d.getDate()).padStart(2, '0')
      const hours = String(d.getHours()).padStart(2, '0')
      const minutes = String(d.getMinutes()).padStart(2, '0')
      const seconds = String(d.getSeconds()).padStart(2, '0')
      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    }
  }
}
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style>